import { Router, RouteRecordRaw, useRouter } from 'vue-router';
import { unref } from 'vue';
import { BasicRouter } from '@/router/types';

/**
 * 捕获router错误
 * @param err
 */
export const handleError = (err?: any) => {
  console.error(err);
};

/**
 * 为了捕获router错误，二次封装router
 * @param _router
 */
export const useGo = (_router = useRouter()) => {
  const { push, replace } = _router;
  return (options: RouteRecordRaw | any, isReplace = false) => {
    isReplace ? replace(options).catch(handleError) : push(options).catch(handleError);
  };
};

/**
 * 刷新二级页面
 * @param _router
 */
export const useRedo = (_router = useRouter()) => {
  const { push, currentRoute } = _router;
  const { params = {}, query, name, fullPath } = unref(currentRoute);
  function redo() {
    return new Promise((resolve, reject) => {
      if (name === BasicRouter.REDIRECT) {
        reject(false);
        return;
      }
      //当有params时 路径可能是 /home/:id/:demo
      //此时使用name跳转
      if (name && Object.keys(params).length > 0) {
        params['_redirect_type'] = 'name';
        params['path'] = String(name);
      } else {
        params['_redirect_type'] = 'path';
        params['path'] = fullPath;
      }
      push({ name: BasicRouter.REDIRECT, params, query }).then(() => resolve(true));
    });
  }
  return redo;
};
